package com.test.singleton.test6;


/**
 * @Author: junwe
 * @Date: 2020/12/6 22:02
 */
public class SingletonTest5 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new GetInstanceThread()).start();
        }
    }
}

/**
 * 静态内部类
 */
class Singleton {
    /**
     * 私有化构造器，外部类不能new对象
     */
    private Singleton() {
    }

    /**
     * 静态内部类
     * 当外部类Singleton被加载的时候，静态内部类SingletonInstance不会马上被加载，保证lazy loading
     */
    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }

    /**
     * 当调用该方法时，SingletonInstance类会被加载，静态常量INSTANCE仅会被加载一次
     *
     * @return
     */
    public static Singleton getInstance() {
        System.out.println(SingletonInstance.INSTANCE.hashCode());
        return SingletonInstance.INSTANCE;
    }
}

class GetInstanceThread implements Runnable {

    @Override
    public void run() {
        Singleton.getInstance();
    }
}
